package com.asurplus.common.sms;

import com.alibaba.fastjson.JSONObject;
import com.asurplus.business.entity.SmsCodeLog;
import com.asurplus.business.service.SmsCodeLogService;
import com.asurplus.common.utils.PhoneUtil;
import com.asurplus.common.utils.RandomUtils;
import com.asurplus.common.utils.ResponseResult;
import com.asurplus.system.entity.SysParamConf;
import com.asurplus.system.service.SysParamConfService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.juncdt.marketsdk.AcrProfile;
import com.juncdt.marketsdk.SendMessageToMultipleDTO;
import com.juncdt.marketsdk.SendMessageToMultipleRequest;
import com.juncdt.marketsdk.SendMessageToMultipleResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 发送验证码工具类
 */
@Component
public class SmsUtils {

    @Autowired
    private SmsCodeLogService smsCodeLogService;
    @Autowired
    private SysParamConfService sysParamConfService;

    @Value("${zhuojianyun.accessKey}")
    private String accessKey;
    @Value("${zhuojianyun.accessSecret}")
    private String accessSecret;
    @Value("${zhuojianyun.verife}")
    private String verife;
    @Value("${zhuojianyun.notice}")
    private String notice;
    @Value("${zhuojianyun.qianming}")
    private String qianming;
    @Value("${zhuojianyun.modelId}")
    private String modelId;

    /**
     * 短信验证码长度
     */
    public static final Integer length = 4;

    /**
     * 发送短信验证码
     */
    public ResponseResult sendSmsCode(String phone) {
        if (StringUtils.isBlank(phone)) {
            return ResponseResult.error("请输入手机号");
        }
        if (!PhoneUtil.isMobileNumberEasy(phone)) {
            return ResponseResult.error("请输入正确的手机号");
        }
        // 构建AcrProfile(可在【我的接口-获取密钥】中找到)
        AcrProfile acrProfile = new AcrProfile(accessKey, accessSecret, verife);
        SendMessageToMultipleDTO dto = new SendMessageToMultipleDTO();
        // 设置短信签名的CODE(您可以在 我的接口-短信设置-签名管理-签名CODE列找到)
        dto.setSignCode(qianming);
        // 设置短信模板的CODE(您可以在 我的接口-短信设置-模板管理-模板CODE列找到)
        dto.setTemplateCode(modelId);
        // 系统参数设置
        SysParamConf sysParamConf = sysParamConfService.saveGetSysParamConf();
        // 生成验证码
        // String redCode = RandomUtils.number(length);
        String redCode;
        // 纯数字
        if (0 == sysParamConf.getSmsCodeType()) {
            redCode = RandomUtils.number(sysParamConf.getSmsCodeLen());
        }
        // 纯字母
        else if (1 == sysParamConf.getSmsCodeType()) {
            redCode = RandomUtils.getString(sysParamConf.getSmsCodeLen());
        }
        // 数字 + 字母
        else if (1 == sysParamConf.getSmsCodeType()) {
            redCode = RandomUtils.getMixString(sysParamConf.getSmsCodeLen());
        }
        // 否则，纯数字
        else {
            redCode = RandomUtils.number(sysParamConf.getSmsCodeLen());
        }
        // 设置模板中的参数（例如：短信模板为 - 您的验证码为${code}）
        Map params = new HashMap();
        params.put("code", redCode);
        dto.setParams(params);
        // 设置需要发送的手机号
        List<String> listPhone = Arrays.asList(phone);
        dto.setPhone(listPhone);
        boolean isSuccess = false;
        int count = 0;
        // 发送短信，响应信息
        SendMessageToMultipleResponse response = null;
        JSONObject resJson = null;
        // 超过三次
        while (3 > count && !isSuccess) {
            // 发送短信
            response = new SendMessageToMultipleRequest(acrProfile, dto).getRpcResponse();
            resJson = JSONObject.parseObject(response.getBody());
            resJson = JSONObject.parseObject(resJson.getString("BusinessException"));
            resJson = JSONObject.parseObject(resJson.getString("message"));
            if ("10000".equals(resJson.getString("verifyCode"))) {
                isSuccess = true;
            } else {
                count++;
            }
        }
        if (isSuccess) {
            // 先把未删除的删掉
            LambdaQueryWrapper<SmsCodeLog> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SmsCodeLog::getPhone, phone);
            queryWrapper.eq(SmsCodeLog::getDelFlag, 0);
            smsCodeLogService.remove(queryWrapper);
            // 存入新的记录
            SmsCodeLog phoneCodeLog = new SmsCodeLog();
            phoneCodeLog.setPhone(phone);
            phoneCodeLog.setCode(redCode);
            smsCodeLogService.save(phoneCodeLog);
            return ResponseResult.success("短信发送成功");
        }
        return ResponseResult.error("短信发送失败");
    }

    /**
     * 验证手机验证码
     * <p>
     * phone 手机号码
     * code 验证码
     */
    public ResponseResult checkSmsCode(String phone, String code) {
        if (StringUtils.isBlank(phone)) {
            return ResponseResult.error("请输入手机号");
        }
        if (!PhoneUtil.isMobileNumberEasy(phone)) {
            return ResponseResult.error("请输入正确的手机号");
        }
        if (StringUtils.isBlank(code)) {
            return ResponseResult.error("请输入验证码");
        }
        LambdaQueryWrapper<SmsCodeLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SmsCodeLog::getPhone, phone);
        queryWrapper.eq(SmsCodeLog::getDelFlag, 0);
        SmsCodeLog smsCodeLog = smsCodeLogService.getOne(queryWrapper, false);
        if (null == smsCodeLog) {
            return ResponseResult.error("验证码已过期");
        }
        if (!code.trim().equals(smsCodeLog.getCode())) {
            return ResponseResult.error("验证码不正确");
        }
        // 验证成功，删除验证码
        smsCodeLogService.removeById(smsCodeLog.getId());
        return ResponseResult.success();
    }
}
